package com.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.domain.common.Comments;
import com.domain.common.Result;
import com.domain.dao.*;
import com.domain.pojo.*;
import com.domain.service.UsersService;
import com.domain.utils.ArithmeticUtil;
import com.domain.utils.DateUtils;
import com.domain.utils.NotNullUtils;
import com.domain.utils.UUIDUtils;
import com.domain.utils.wyyx.IMSet;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Service
public class UsersServiceImpl implements UsersService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private PublishMapper publishMapper;
    @Autowired
    private PublishAcceptanceMapper publishAcceptanceMapper;

    @Autowired
    private UsersHelpMapper usersHelpMapper;

    @Autowired
    private UsersWalletMapper usersWalletMapper;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private UsersFillterUsersMapper usersFillterUsersMapper;

    @Autowired
    private ContactsMapper contactsMapper;


    /**
     * 修改个人信息
     *
     * @param userId
     * @param nickName
     * @param image
     * @param name
     * @param gender
     * @param birthday
     * @param city
     * @param industry
     * @param personalLabel
     * @param headImage
     * @param request
     */
    @Override
    public Result editUserInfo(String userId, String nickName, String image, String name, String gender, String birthday, String city, String industry, String personalLabel, String headImage, HttpServletRequest request) throws IOException {
        Users user = new Users();
        user.setId(userId);
        if (NotNullUtils.isNotNullObject(nickName)) {
            user.setNickname(nickName);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(image)) {
            user.setImage(image);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(name)) {
            //更改im信息
            IMSet.updateUser(userId, name, "", "", "", "");
            user.setName(name);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(gender)) {
            //更改im信息
            IMSet.updateUser(userId, "", "", "", "", gender);
            user.setGender(new Integer(gender));
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(birthday)) {
            //更改im信息
            IMSet.updateUser(userId, "", "", birthday, "", "");
            user.setBirthday(DateUtils.strToDate(birthday, "yyyy-MM-dd"));
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(city)) {
            user.setCity(city);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(industry)) {
            user.setIndustry(industry);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(personalLabel)) {
            user.setPersonalLabel(personalLabel);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        if (NotNullUtils.isNotNullObject(headImage)) {
            //更改im信息
            IMSet.updateUser(userId, "", headImage, "", "", "");
            user.setHeadImage(headImage);
            usersMapper.updateByPrimaryKeySelective(user);
        }
        return Result.success("操作成功", user);

    }

    /**
     * 修改手机号码
     *
     * @param userId
     * @param newPhoneNum
     */
    @Override
    public Result changePhoneNum(String userId, String newPhoneNum) throws IOException {
        //判断手机号是否注册
        int resultCount = usersMapper.selectByPhone(newPhoneNum);
        if (resultCount > 0) {
            return Result.publicResult(Comments.ILLEGAL_ARGUMENT, "手机号已经注册！");
        }
        Users users = new Users();
        users.setId(userId);
        users.setPhone(newPhoneNum);
        usersMapper.updateByPrimaryKeySelective(users);
        IMSet.updateUser(userId, "", "", "", newPhoneNum, "");
        return Result.success();
    }

    /**
     * 我的
     *
     * @param userId
     * @return
     */
    @Override
    public Result getUsersPageInfo(String userId) {
        Map<String, Object> maps = new HashMap<>();
        Users user = usersMapper.selectByPrimaryKey(userId);
        maps.put("userId", user.getId());
        maps.put("userHeadImage", user.getHeadImage());
        maps.put("userName", user.getName());
        maps.put("userNickName", user.getNickname());
        //获取我得发布条数
        List<Publish> publishes = publishMapper.selectPublishByUserId(user.getId());
        maps.put("userPublishSize", publishes.size());
        //获取我的帮忙条数
        List<Map<String, Object>> publishAcceptances = publishAcceptanceMapper.selectByUserId(user.getId());
        maps.put("userPublishAcceptancesSize", publishAcceptances.size());
        //获取我的帮转条数
        List<Map<String, Object>> helps = usersHelpMapper.selectByUsersId(user.getId());
        maps.put("userHelpSize", helps.size());
        //获取我的靠谱值
        maps.put("spectralValue", user.getSpectralValue());
        return Result.success("操作成功", maps);
    }

    /**
     * 编辑我的发布
     *
     * @param userToken    用户token
     * @param userId       用户id
     * @param publishId    发布id
     * @param title        发布title
     * @param content      发布类容
     * @param images       发布照片
     * @param filterUserId 过滤得好友
     * @param longitude    发布位置经度
     * @param latitude     发布位置纬度
     * @param cityName     发布城市名称
     * @param itIsPaid     发布是否有偿
     * @param typeId       发布类型id
     * @return
     */
    @Override
    public Result editUsersPublish(String userToken, String userId, String publishId, String title, String content, String images, String filterUserId, String longitude, String latitude, String cityName, String itIsPaid, String typeId) {
        //修改我的发布
        Publish ps = new Publish();
        ps.setId(publishId);
        ps.setUpdateTime(new Date());
        ps.setUserId(userId);
        ps.setTitle(title);
        ps.setLongitude(longitude);
        ps.setLatitude(latitude);
        ps.setCityName(cityName);
        ps.setContent(content);
        ps.setImages(images);
        ps.setFilterUserId(filterUserId);
        ps.setItIsPaid(new Integer(itIsPaid));
      /*  ps.setSpareTwo(new BigDecimal(money));*/
        ps.setSpareOne(typeId);
        publishMapper.updateByPrimaryKeySelective(ps);
        return Result.success();
    }

    /**
     * 获取用户账单明细
     *
     * @param userId
     * @param startTime
     * @param endTime
     * @param pageNum
     * @param pagaSize
     * @return
     */
    @Override
    public Result getUserBillDetail(String userId, String startTime, String endTime, String pageNum, String pagaSize) {
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId", userId);
        maps.put("startTime", startTime);
        maps.put("endTime", endTime);
        PageHelper.startPage(new Integer(pageNum), new Integer(20));
        List<Bill> bills = billMapper.selectByUsersId(maps);

        Map<String, Object> map = new HashMap<>();
        PageInfo pageInfo = new PageInfo(bills);
        double out = 0;
        double put = 0;
        for (Bill b : bills) {
            //支出
            if (Comments.SERZERBAL_OUT.equals(b.getBillType())) {
                out = ArithmeticUtil.sub(out, b.getBillMoney().doubleValue());
            }
            //收入
            if (Comments.SERZERBAL_PUT.equals(b.getBillType())) {
                put = ArithmeticUtil.sub(out, b.getBillMoney().doubleValue());
            }
        }
        map.put("billList", pageInfo.getList());
        map.put("outMoney", out);
        map.put("putMoney", put);
        return Result.success("操作成功", map);
    }

    /**
     * 屏蔽好友
     *
     * @param userId         用户id
     * @param fillterUserIds 过滤得好友id
     * @param fillterType    屏蔽类型（1 屏蔽好友  2 切断人脉链（我好友发布得信息也看不见））
     * @return
     */
    @Override
    public Result fillterUsers(String userId, String fillterUserIds, String fillterType) {
        JSONArray json = JSON.parseArray(fillterUserIds);//todo
        Iterator it = json.iterator();
        while (it.hasNext()) {
            JSONObject sObj = (JSONObject) it.next();
            UsersFillterUsers us = new UsersFillterUsers();
            String ids = (String) sObj.get("fillterUserIds");
            us.setId(UUIDUtils.getRandomUUID());
            us.setCreatTime(new Date());
            us.setFillerUserId(ids);
            us.setFillterType(fillterType);
            us.setUserId(userId);
            usersFillterUsersMapper.insertSelective(us);
        }
        return Result.success();
    }

    //判断是否是好友
    @Override
    public boolean itIsUsersFriends(String userId, String usersFridens) {
        List<Contacts> contacts = contactsMapper.selectByUsersIdAndType(userId);
        for (Contacts c : contacts
                ) {
            if (usersFridens.equals(c.getSpareTwo())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取人脉链关系
     *
     * @param usersId   用户id
     * @param friendsId 好友id
     * @return
     */
    @Override
    public List<Users> getUsersHumanChain(String usersId, String friendsId) {
        return null;
    }


}


